package com.hmdp.service.impl;

import cn.hutool.core.io.resource.StringResource;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.RedisAccessor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HSJ
 * @since 2023-02-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryTypeList() {
        log.debug(">>>>>>>>查询 店铺 类型" +
                "先从 redis 获取 list");
        String key = RedisConstants.TYPE_SHOP_LIST;
        String typeShopJson = stringRedisTemplate.opsForValue().get(key);
        log.debug("判断 redis是否有 该list");
        if(StrUtil.isNotBlank(typeShopJson)){
            log.debug("redis 有 该list，直接返回 shopType <<<<<");
            JSONArray jsonArray = JSONUtil.parseArray(typeShopJson);
            List<ShopType> typeList = JSONUtil.toList(jsonArray, ShopType.class);
            return Result.ok(typeList);
        }
        log.debug("redis 没有 该list， 查询数据库");
        List<ShopType> typeList = query().orderByAsc("sort").list();
        log.debug(" 将查到的数据 写入 redis");
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(typeList));
        log.debug("返回查到的数据 <<<<<<<<<<<");
        return  Result.ok(typeList);
    }
}
